﻿using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using  Identity.Models;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;



namespace Identity.Contexts;

public partial class SysContext(DbContextOptions<SysContext> options) : IdentityDbContext<User,Role,string,IdentityUserClaim<string>,UserRole,IdentityUserLogin<string>,IdentityRoleClaim<string>,IdentityUserToken<string>>(options)
{
    public virtual DbSet<Role> Roles { get; set; }
    public virtual DbSet<Identity.Models.Navigation> Navigationlists { get; set; }
    public virtual DbSet<User> Users { get; set; }
 
    public virtual DbSet<UserRole> UserRoles    { get; set; }
    public virtual DbSet<NavigationRole> Navigationroles { get; set; }
     protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .UseCollation("utf8mb4_0900_ai_ci")
            .HasCharSet("utf8mb4");
 
  
        modelBuilder.Entity<Identity.Models.Navigation>(entity =>
        {
            entity.HasKey(e => e.Id).HasName("PRIMARY");
        });
         modelBuilder.Entity<NavigationRole>(entity =>
        {
            entity.HasKey(e => e.Id).HasName("PRIMARY");
        });
        OnModelCreatingPartial(modelBuilder);
  
        modelBuilder.Entity<NavigationRole>(entity =>
        {
            entity.HasKey(e => e.Id).HasName("PRIMARY");

            entity.HasOne(d => d.Navigation).WithMany(p => p.NavigationRoles).HasConstraintName("navigationrole_ibfk_1");

            entity.HasOne(d => d.Role).WithMany(p => p.NavigationRoles).HasConstraintName("navigationrole_ibfk_2");
        });
    
            // 配置其他 Identity 实体（如果需要）
        modelBuilder.Entity<IdentityUserLogin<string>>(entity =>
        {
            entity.HasKey(login => new { login.LoginProvider, login.ProviderKey });
        });
            modelBuilder.Entity<IdentityUserToken<string>>(entity =>
            {
                entity.HasKey(token => new { token.UserId, token.LoginProvider, token.Name });
            });
          modelBuilder.Entity<UserRole>()
                .HasKey(ur => new { ur.UserId, ur.RoleId });

            // 配置 User 和 Role 的多对多关系
            modelBuilder.Entity<User>(
                entity =>
                {
                    entity.HasMany(u => u.UserRoles)
                    .WithOne(ur => ur.User)
                    .HasForeignKey(ur => ur.UserId);

                    entity.Property(e=>e.NotificationType).HasConversion<string>()
                    .HasMaxLength(20);
                    
                });
  
                

        //
            modelBuilder.Entity<Role>()
                .HasMany(r => r.UserRoles)
                .WithOne(ur => ur.Role)
                .HasForeignKey(ur => ur.RoleId);
 

    }

    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}
